// src/services/authService.ts
import api from './api';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { User } from '../types';
import { Platform } from 'react-native';

interface LoginResponse {
  token: string;
  refreshToken: string;
  user: User;
}

interface RegisterRequest {
  email: string;
  username: string;
  password: string;
  verificationCode?: string;
}

interface RegisterResponse {
  token: string;
  refreshToken: string;
  user: User;
}

interface BackendAuthResponse {
  userId: number;
  email: string;
  username: string;
  token: string;
  refreshToken: string;
  timestamp: string,
}

class AuthService {
  // 登录
  async login(email: string, password: string): Promise<LoginResponse> {
    const deviceInfo = await this.getDeviceInfo();

    const response = await api.post<BackendAuthResponse>('/auth/user/login', {
      email,
      password,
      deviceInfo,
    });

    const authData = this.transformBackendResponse(response.data);

    // 保存token
    await this.saveAuthData(authData);

    return authData;
  }

  // 注册
  async register(data: RegisterRequest): Promise<RegisterResponse> {
    const response = await api.post<BackendAuthResponse>('/auth/user/register', data);

    const authData = this.transformBackendResponse(response.data);

    // 保存token
    await this.saveAuthData(authData);

    return authData;
  }

  private transformBackendResponse(backendData: BackendAuthResponse): LoginResponse | RegisterResponse {
    return {
      token: backendData.token,
      refreshToken: backendData.refreshToken,
      user: {
        id: backendData.userId,
        email: backendData.email,
        username: backendData.username,
        avatarUrl: '',
        createdAt: backendData.timestamp,
        emailVerified: true, // 注册成功默认已验证
      }
    };
  }

  // 登出
  async logout(): Promise<void> {
    try {
      await api.post('/auth/user/logout');
    } catch (error) {
      console.error('Logout error:', error);
    } finally {
      await this.clearAuthData();
    }
  }

  // 获取用户信息
  async getUserInfo(): Promise<User> {
    const response = await api.get<User>('/auth/user/info');
    return response.data;
  }

  // 更新用户资料
  async updateProfile(data: { username?: string; avatarUrl?: string }): Promise<User> {
    const response = await api.put<User>('/auth/user/profile', data);
    return response.data;
  }

  // 修改密码
  async changePassword(oldPassword: string, newPassword: string): Promise<void> {
    await api.post('/auth/user/change-password', {
      oldPassword,
      newPassword,
    });
  }

  // 发送注册验证码
  async sendRegisterCode(email: string): Promise<void> {
    await api.post('/auth/user/send-register-code', { email });
  }

  // 发送密码重置验证码
  async sendResetCode(email: string): Promise<void> {
    await api.post('/auth/user/send-reset-code', { email });
  }

  // 忘记密码
  async forgotPassword(email: string): Promise<void> {
    await api.post('/auth/user/forgot-password', { email });
  }

  // 重置密码
  async resetPassword(email: string, code: string, newPassword: string): Promise<void> {
    await api.post('/auth/user/reset-password', {
      email,
      code,
      newPassword,
    });
  }

  // 刷新Token
  async refreshToken(): Promise<string> {
    const refreshToken = await AsyncStorage.getItem('refreshToken');
    if (!refreshToken) {
      throw new Error('No refresh token');
    }

    const response = await api.post<{ token: string; refreshToken: string }>(
      '/auth/user/refresh-token',
      { refreshToken }
    );

    if (response.data.token) {
      await AsyncStorage.setItem('token', response.data.token);
    }
    if (response.data.refreshToken) {
      await AsyncStorage.setItem('refreshToken', response.data.refreshToken);
    }

    return response.data.token;
  }

  // 保存认证数据
  private async saveAuthData(data: LoginResponse | RegisterResponse): Promise<void> {
    try {
      // 只有当值存在且不为 null/undefined 时才保存
      if (data.token) {
        await AsyncStorage.setItem('token', data.token);
      }

      if (data.refreshToken) {
        await AsyncStorage.setItem('refreshToken', data.refreshToken);
      }

      if (data.user) {
        await AsyncStorage.setItem('user', JSON.stringify(data.user));
      }

      console.log('✅ Auth data saved successfully');
    } catch (error) {
      console.error('❌ Failed to save auth data:', error);
      throw error;
    }
  }

  // 清除认证数据
  private async clearAuthData(): Promise<void> {
    await AsyncStorage.multiRemove(['token', 'refreshToken', 'user']);
  }

  async loadAuthData(): Promise<{
    token: string | null;
    refreshToken: string | null;
    user: User | null;
  }> {
    try {
      const [token, refreshToken, userString] = await AsyncStorage.multiGet([
        'token',
        'refreshToken',
        'user'
      ]);

      const user = userString[1] ? JSON.parse(userString[1]) : null;

      return {
        token: token[1],
        refreshToken: refreshToken[1],
        user,
      };
    } catch (error) {
      console.error('❌ Failed to load auth data:', error);
      return {
        token: null,
        refreshToken: null,
        user: null,
      };
    }
  }

  // 获取设备信息
  private async getDeviceInfo(): Promise<string> {
    // 这里可以使用 react-native-device-info 库获取更详细的设备信息
    return `${Platform.OS} ${Platform.Version}`;
  }
}

export default new AuthService();